const getToken = () => {
	// #ifdef MP
	return getMpToken();
	// #endif

	// #ifdef H5
	console.log('这是H5');
	// throw new Error();
	return getApp().globalData.token;
	// #endif
}

const getMpToken = async () => {
	return new Promise(async (res, rej) => {
		let token = getApp().globalData.token;
		if (token) {
			res(token);
			return;
		}
		let tokenStorage = uni.getStorageSync("token");
		if (tokenStorage) {
			getApp().globalData.token = tokenStorage;
			res(tokenStorage);
			return;
		}
		res(null);
	})
	// return new Promise(async (res, rej) => {
	// 	let token = getApp().globalData.token;
	// 	if (token) {
	// 		res(token);
	// 		return;
	// 	}
	// 	let tokenStorage = uni.getStorageSync("token");
	// 	if (tokenStorage) {
	// 		try {
	// 			let checkSession = await uni.checkSession();
	// 			if (checkSession.errMsg != 'checkSession:ok') {
	// 				throw new Error("session过期");
	// 			}
	// 			getApp().globalData.token = tokenStorage;
	// 			token = tokenStorage;
	// 			res(token);
	// 			return;
	// 		} catch (err) {
	// 			uni.removeStorage({
	// 				key: 'token'
	// 			})
	// 		}
	// 	}
	// 	try {
	// 		let {
	// 			code
	// 		} = await uni.login();
	// 		let url, appId;

	// 		// #ifdef MP-WEIXIN
	// 		url = 'member/wxCodeLogin';
	// 		appId = 'wxbc8c2feaa45add1d';
	// 		// #endif
	// 		let {
	// 			data = {}
	// 		} = await post(url, {
	// 			jsCode: code,
	// 			appId
	// 		}, null);
	// 		token = data.token;
	// 		getApp().globalData.token = token;
	// 		uni.setStorage({
	// 			key: 'token',
	// 			data: token
	// 		});
	// 		res(token);
	// 		return;
	// 	} catch (err) {
	// 		uni.showModal({
	// 			title: '提示',
	// 			showCancel: false,
	// 			confirmText: '我知道了',
	// 			content: err,
	// 			complete() {
	// 				// uni.exitMiniProgram();
	// 			}
	// 		})
	// 		rej(err);
	// 		return;
	// 	}
	// })
}

const request = async (url, method, params = {}, loadingTitle = '请稍候...', type) => {
	let token = null;
	if (!url.startsWith('member/wxCodeLogin')) {
		token = await getToken();
	}
	uni.showNavigationBarLoading();
	return new Promise((resolve, reject) => {
		if (loadingTitle) {
			uni.showLoading({
				title: loadingTitle,
				mask: true,
			})
		}
		let _keys = [];
		for (let key in params) {
			if (!params[key] && params[key] != 0) {
				_keys.push(key);
			}
		}
		for (let key of _keys) {
			delete params[key];
		}
		uni.request({
			url: url.startsWith('http') ? url : (getApp().globalData.baseApi + url),
			method: method,
			timeout: 10000,
			data: params,
			header: {
				'content-type': type == 'String' ?
					'application/x-www-form-urlencoded;charset=UTF-8' :
					'application/json;charset=UTF-8',
				'X-Access-Token': token,
				// #ifdef MP-WEIXIN
				'channel': 'wxxcx'
				// #endif
				// #ifdef MP-ALIPAY
				'channel': 'alixcx'
				// #endif
			},
			success(res) {
				if (loadingTitle) {
					uni.hideLoading();
				}
				console.log("响应》》》", res)
				if (res.statusCode != 200) {
					uni.showToast({
						title: '操作失败',
						icon: 'error',
						duration: 2000
					})
					reject(res);
					return;
				}
				if (res.data.code == 200 || res.data.code == 512 || res.data.code == 514) {
					res.data = res.data || {}
					resolve(res.data)
				} else if (res.data.code == 302) { //token失效  未登陆或登陆失败,或IP地址改变
					uni.showModal({
						title: '提示',
						content: res.data.message,
						showCancel: false,
						confirmText: '我知道了'
					})
					reject();
				} else if (res.data.code == 100) { //token失效  未登陆或登陆失败,或IP地址改变
					// #ifdef MP
					getApp().globalData.token = null;
					uni.removeStorageSync('token')
					request(url, method, params, loadingTitle, type).then(data => {
						resolve(data)
					}).catch(err => {
						reject(err);
					});
					// #endif
				} else if (res.data.code == 510) {
					uni.showToast({
						title: "请先登录",
						icon: 'none',
						duration: 1500
					})
					setTimeout(() => {
						uni.navigateTo({
							url: "/pages/login/login"
						})
					}, 1500)
					reject(res)
					return;
				} else if (res.data.code == 103) {
					uni.showToast({
						title: res.data.message,
						icon: 'none',
						duration: 1500
					})
					setTimeout(() => {
						uni.navigateTo({
							url: res.data.data
						})
					}, 1500)
					reject(res)
					return;
				} else { //其他情况
					let error = res.data.message || '未知异常\n请重试';
					uni.showToast({
						title: error,
						icon: error.length <= 7 ? 'error' : 'none',
						duration: 3000,
					})
					reject(error)
					return;
				}
			},
			fail(error) {
				if (loadingTitle) {
					uni.hideLoading();
				}
				console.log("异常》》》", error)
				if (error.errMsg != 'request:fail' && error.errMsg !=
					'request:fail abort statusCode:-1 似乎已断开与互联网的连接。(-1009)') {
					uni.showToast({
						title: error.message || error.data.message || '未知异常\n请重试',
						icon: 'error',
						duration: 2000
					})
				}
				reject(error);
			},
			complete(res) { //成功失败后
				uni.hideNavigationBarLoading();
			}
		})
	});
}

/**
 * 封装微信的上传接口
 */
const wxUpload = (url, filePath, formData = {}) => {
	return new Promise(function(resolve, reject) {
		const uploadTask = uni.uploadFile({
			url,
			filePath,
			name: 'file',
			formData,
			success(res) {
				if (res.statusCode == 200 || res.statusCode == 204) {
					return resolve(res)
				} else {
					return reject(res);
				}
			},
			fail(res) {
				return reject(res)
			},
			complete(res) {}
		})
		// uploadTask.onProgressUpdate((res) => {
		//   console.log('上传进度', res.progress)
		//   console.log('已经上传的数据长度', res.totalBytesSent)
		//   console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
		// })
		//uploadTask.abort() // 取消上传任务
	});
}
/**
 * 
 * @param {*} dir:文件目录
 * @param {*} files:[{name: '字段名',multiple: true：多文件；false：单文件,pathList: ['上传的文件目录']}]
 */

import util from '@/utils/util.js';
const uploadFile = async (dir, files) => {
	if (!files || files.length == 0) {
		return;
	}
	let date = new Date();
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	dir = dir + '/' + year + '/' + (month < 10 ? ('0' + month) : month) + '/' + (day < 10 ? ('0' + day) : day);
	return new Promise(async (resolve, reject) => {
		//获取OSS密钥
		let {
			data: ossData
		} = await get('common/oss_signature', {
			dir
		}, '文件上传中...');
		uni.showLoading({
			title: '文件上传中...',
			mask: true
		})
		let host = ossData.host;
		dir = ossData.dir; //因为可能后端会编辑文件夹，比如按用户归类
		let uploadList = [];
		for (let i of files) {
			i.ossList = [];
			for (let f of i.pathList) {
				if (f) {
					if (f.startsWith(host)) { //原OSS文件，直接返回，但有可能发生多个数据引用同一文件的情况
						i.ossList.push(f); //OSS地址
						continue;
					}
					let path = dir + '/' + util.UUID() + '.' + util.getSuffix(f);
					i.ossList.push(host + path); //OSS地址
					uploadList.push(wxUpload(host, f, {
						'key': path,
						'policy': ossData.policy,
						'OSSAccessKeyId': ossData.OSSAccessKeyId,
						'signature': ossData.signature,
						'success_action_status': '200'
					}))
				} else {
					i.ossList.push(null); //OSS地址
					continue;
				}
			}
		}
		Promise.all(uploadList).then(res => {
			uni.hideLoading();
			resolve(files);
		}).catch(err => {
			uni.hideLoading();
			uni.showToast({
				title: '文件上传失败\n请重试',
				icon: 'error',
				duration: 2000
			})
			reject(err);
		})
	})
}

const get = (url, params, loadingTitle = '努力加载中...', type) => {
	return request(url, "GET", params, loadingTitle, type);
}
const del = (url, params, loadingTitle = '删除中...', type) => {
	return request(url, "DELETE", params, loadingTitle, type);
}
const post = (url, params, loadingTitle = '新增中...', type) => {
	return request(url, "POST", params, loadingTitle, type);
}
const put = (url, params, loadingTitle = '保存中...', type) => {
	return request(url, "PUT", params, loadingTitle, type);
}

export default {
	get,
	post,
	put,
	del,
	uploadFile
}